package com.starmark.gateway.project.provider.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.starmark.core.framework.base.AbstractBaseService;
import com.starmark.core.framework.util.BeanMapper;
import com.starmark.gateway.project.provider.dto.GatewayProjectSpecUrlDto;
import com.starmark.gateway.project.provider.entity.GatewayProjectSpecUrl;
import com.starmark.gateway.project.provider.mapper.GatewayProjectSpecUrlMapper;
import com.starmark.gateway.project.provider.service.IGatewayProjectSpecUrlService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.io.Serializable;
import java.util.Map;

/**
 * <p>
 * 工程特定网址管理 服务实现类
 * </p>
 *
 * @author starmark
 * @since 2020-09-29
 */
@Service
public class GatewayProjectSpecUrlServiceImpl extends AbstractBaseService<GatewayProjectSpecUrlMapper, GatewayProjectSpecUrl> implements IGatewayProjectSpecUrlService {

    private final static String PROJECT_SPECURL_REDIS_KEY = "starmark:gateway:project:specurl:";


    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Override
    public void buildPageSearch(Map<String, Object> params, QueryWrapper<GatewayProjectSpecUrl> eWrapper) {
        if (params.get("keyword") != null && StrUtil.isNotEmpty(params.get("keyword") + "")) {
            eWrapper.like("name", params.get("keyword") + "");
        }

        eWrapper.like("project_id",params.get("project_id")+"");


    }

    @Override
    public boolean save(GatewayProjectSpecUrl entity){
        boolean result= super.save(entity);
        redisTemplate.opsForHash().putIfAbsent(PROJECT_SPECURL_REDIS_KEY+entity.getProjectId(),entity.getId(),  JSONObject.toJSONString(BeanMapper.map(entity, GatewayProjectSpecUrlDto.class)));
        return result;
    }

    @Override
    public boolean updateById(GatewayProjectSpecUrl entity) {
        boolean result= super.updateById(entity);
        redisTemplate.opsForHash().put(PROJECT_SPECURL_REDIS_KEY+entity.getProjectId(),entity.getId(), JSONObject.toJSONString( BeanMapper.map(entity, GatewayProjectSpecUrlDto.class)));

        return result;
    }
    /**
     * 根据 ID 删除
     *
     * @param id 主键ID
     */
    @Override
    public  boolean removeById(Serializable  id) {
        GatewayProjectSpecUrl gatewayProjectSpecUrl=this.getById(id);
        Assert.notNull(gatewayProjectSpecUrl,"特别管理URL不允许为空:"+id);
        boolean result= super.removeById(id);
        redisTemplate.opsForHash().delete(PROJECT_SPECURL_REDIS_KEY+gatewayProjectSpecUrl.getProjectId(),gatewayProjectSpecUrl.getId());
        return result;
    }
}
